<template>
  <div
    class="flex h-100% ml-20px"
    style="background-color: #fff; border-radius: 10px"
  >
    <!-- 左侧树形菜单 -->
    <!-- <ContentWrap :class="['!w-[var(--left-tree-max-width)] px-0px tree-min-width']"> -->
      <div class="mt-20px ">
            <div class="mb-10px" style="margin-bottom:27px">

        <el-upload
          class="mr-12px ml-15px "
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"

          :on-change="(file) => handleFileChange(file, 'packet')"
        >
        <!--  :accept="'.xlsx,.xls'" -->
          <BaseButton class="opBtn" size="" type="primary"
            >导入数据包</BaseButton
          >
        </el-upload>
        <BaseButton class="opBtn" size="" type="primary" @click="exportAction">
          导出数据包
        </BaseButton>
      </div>
       <ElDivider />
         <div class="flex-1 mb-15px ml-15px f-s16 font-bold">任务名称</div>
        <!-- <div class="text-18px font-bold mb-10px mt-15px ml-15px">任务列表</div> -->
      <ElTree
      style="margin-left:15px"
      :class="['!w-[var(--left-tree-max-widths)] px-0px tree-min-width']"
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="missionCode"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'name',
          class: customNodeClass,
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div
            :title="data.name"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.name }}【{{ data.superiorExportTime.slice(0, 10) }}】
          </div>
        </template>
      </ElTree>
      </div>
    <!-- </ContentWrap> -->

    <!-- 右侧内容区域 -->
      <div
      class="tableManage ml-20px"
      style="width: calc(100% - var(--left-tree-max-widths))"
    >
    <ContentWrap >
      <!-- 搜索区域 -->
      <div class="search-form">
        <Search
          :schema="allSchemas.searchSchema"
          @reset="setSearchParams"
          @search="setSearchParams"
        />
      </div>
  <ElDivider />
      <!-- 操作按钮区域 -->


      <!-- 数据表格 -->
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{ total }"
      />
    </ContentWrap>

    <!-- 对话框 -->
    <Dialog v-model="dialogVisible" :title="dialogTitle" :width="actionType === 'detail'?'85%':'1000px'">
      <!-- 查看详情 -->
      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <!-- 创建采集任务 -->
      <Task v-if="actionType === 'task'" ref="taskRef" :show-checkbox="true" />

      <!-- 对话框底部按钮 -->
      <template #footer>
        <BaseButton
          v-if="actionType === 'task'"
          type="primary"
          :loading="saveLoading"
          @click="saveTask"
        >
          保存
        </BaseButton>
        <BaseButton @click="dialogVisible = false">关闭</BaseButton>
      </template>
    </Dialog>

    <Dialog v-model="resultDialogVisible" title="导入失败" width="50%">
      <div class="import-result">
        <el-tabs
          v-for="(value, index) in tabs"
          :key="index"
          v-model="activeName"
          @tab-click="handleClick"
        >
          <el-tab-pane :label="value.tab" :name="value.tab">
            <div v-if="value.errors.length > 0" class="error-details">
              <h3 class="mb-10px">错误详情：</h3>
              <div
                class="error-item"
                v-for="(error, index) in value.errors"
                :key="index"
              >
                <h4 class="mb-10px">{{ error.dataRow }}:</h4>
                <p class="mb-5px" v-for="(item, i) in error.errors" :key="i">
                  {{ item }}
                </p>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <BaseButton type="primary" @click="resultDialogVisible = false">
          确定
        </BaseButton>
      </template>
    </Dialog>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { ContentWrap } from "@/components/ContentWrap";
import { Table } from "@/components/Table";
import { ref, unref, nextTick, watch, reactive, onMounted, onUnmounted } from "vue";
import {
  ElMessage,
  ElTree,
  ElUpload,
  UploadFile,
  UploadInstance,
} from "element-plus";
import * as XLSX from "xlsx";


import type { DepartmentItem ,DepartmentUserItem} from "@/components/DepartmentTree/types";
import { useTable } from "@/hooks/web/useTable";
import { Search } from "@/components/Search";
import Detail from "./components/collectionTaskManagmentDetail.vue";
import Task from "./components/task.vue";
import { Dialog } from "@/components/Dialog";

import { CrudSchema, useCrudSchemas } from "@/hooks/web/useCrudSchemas";
import { BaseButton } from "@/components/Button";

// ============ 常量定义 ============
const STORAGE_KEY = "current_node_key"; // localStorage存储键名

// ============ 响应式数据定义 ============

// 树形结构相关
const treeEl = ref<typeof ElTree>();
const departmentList = ref<DepartmentItem[]>([]);
const currentNodeKey = ref(localStorage.getItem(STORAGE_KEY) || "");
const currentDepartment = ref("");

// 表格相关
const { tableRegister, tableState, tableMethods } = useTable({
  /**
   * 获取表格数据的API
   */
  fetchDataApi: async () => {
    // 如果没有选中节点或部门列表为空，不调用接口
    if (!currentNodeKey.value || departmentList.value.length === 0) {
      return {
        list: [],
        total: 0,
      };
    }

    const { pageSize, currentPage } = tableState;
    const res = await "/api/mission/getMissionsByMissionCode".get({
      missionCode: currentNodeKey.value,
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
      manufacturer: (unref(searchParams) as any).collectorUserName || "",
    });
    return {
      list: res.data.records || [],
      total: res.data.total || 0,
    };
  },
});

const { total, loading, dataList, pageSize, currentPage } = tableState;
const { getList, getElTableExpose, delList } = tableMethods;

// 搜索参数
const searchParams = ref({});

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const currentRow = ref<DepartmentUserItem>();
const actionType = ref("");
const taskRef = ref<ComponentRef<typeof Task>>();
const tabs = ref();
const activeName = ref("");
// 加载状态
const saveLoading = ref(false);
const importLoading = ref(false);

// 导入相关
const resultDialogVisible = ref(false);
const uploadRef = ref<UploadInstance>();
const selectedFile = ref<File | null>(null);
const handleClick = (tab, event) => {
        console.log(tab, event);
      }
// 导入结果
const importResult = reactive({
  success: false,
  successCount: 0,
  failCount: 0,
  message: "",
  errors: [] as Array<{ row: number; message: string }>,
});

// ============ CRUD表结构配置 ============

/**
 * 任务管理表结构配置
 */
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: "selection",
    width: 55,
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: "selection", hidden: true },
  },
  {
    field: "index",
    label: "序号",
    width: 55,
    form: { hidden: true },
    search: { hidden: true },
    detail: { hidden: true },
    table: { type: "index" },
  },
  {
    field: "name",
    label: "任务名称",
    search: { hidden: true },
  },
  {
    field: "superiorUserName",
    label: "数据包导出人员",
    search: { hidden: true },
  },
  {
    field: "validTime",
    label: "有效日期截止",
    search: { hidden: true },
  },
  {
    field: "collectorUserName",
    label: "成品厂名称",
    search: {
      componentProps: {
        placeholder: "成品厂名称",
      },
    },
  },
  {
    field: "collectorImportTime",
    label: "成品厂导入时间",
    search: { hidden: true },
  },
  {
    field: "collectorExportTime",
    label: "成品厂导出时间",
    detail: { hidden: true },
    search: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "approver",
    label: "成品厂审批人",
    search: { hidden: true },
    form: {
      component: "Select",
      value: [],
      componentProps: {
        multiple: true,
        collapseTags: true,
        maxCollapseTags: 1,
      },
      // optionApi: async () => {
      //   const res = await getRoleListApi();
      //   return res.data?.list?.map((v) => ({
      //     label: v.roleName,
      //     value: v.id,
      //   }));
      // },
    },
  },
  {
    field: "approveTime",
    label: "成品厂审批时间",
    form: { component: "Input" },
    search: { hidden: true },
  },
  {
    field: "superiorImportTime",
    label: "数据包导入时间",
    form: { component: "Input" },
    search: { hidden: true },
  },
  {
    field: "action",
    label: "操作",
    form: { hidden: true },
    detail: { hidden: true },
    search: { hidden: true },
    table: {
      width: 100,
      slots: {
        default: (data: any) => {
          const row = data.row as DepartmentUserItem;
          return (
            <>
              <div style="display:flex;color: var(--el-color-primary)">
                <div
                  class="flex-1 cursor-pointer"
                  onClick={() => action(row, "detail")}
                >
                  查看
                </div>
              </div>
            </>
          );
        },
      },
    },
  },
]);

const { allSchemas } = useCrudSchemas(crudSchemas);

// ============ 监听器 ============

/**
 * 监听当前部门变化，用于树过滤
 */
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val);
  }
);

// ============ 方法定义 ============

/**
 * 自定义树节点类名
 * @param data 节点数据
 * @param node 节点对象
 * @returns 类名字符串
 */
const customNodeClass = (data: DepartmentItem, node: any) => {
  return node.isCurrent ? "is-current-node" : "";
};

/**
 * 获取部门/任务树数据
 */
const fetchDepartment = async () => {
  const res = await "/api/mission/distinct".get();

  // 处理数据，确保有children属性
  res.data.records.forEach((item) => {
    item.children = [];
  });
  departmentList.value = res.data.records || [];

  // 恢复之前选中的节点或设置默认选中第一个节点
  const savedKey = localStorage.getItem(STORAGE_KEY);
  if (
    savedKey &&
    departmentList.value.some((item) => item.missionCode === savedKey)
  ) {
    currentNodeKey.value = savedKey;
  } else if (res.data.records.length > 0) {
    currentNodeKey.value = res.data.records[0].missionCode;
    localStorage.setItem(STORAGE_KEY, currentNodeKey.value);
  }

  await nextTick();

  // 设置当前选中的节点并加载数据
  if (currentNodeKey.value) {
    unref(treeEl)?.setCurrentKey(currentNodeKey.value);
    if (departmentList.value.length > 0) {
      getList();
    }
  }
};

/**
 * 树节点过滤方法
 * @param value 过滤值
 * @param data 节点数据
 * @returns 是否匹配
 */
const filterNode = (value: string, data: DepartmentItem) => {
  if (!value) return true;
  return data.departmentName?.includes(value) || false;
};

/**
 * 树节点选择变化事件
 * @param data 选中的节点数据
 */
const currentChange = (data: DepartmentItem) => {
  if (!data) return;

  currentNodeKey.value = data.missionCode;
  localStorage.setItem(STORAGE_KEY, data.missionCode);
  currentPage.value = 1;
  getList();
};

/**
 * 设置搜索参数并刷新表格
 * @param params 搜索参数
 */
const setSearchParams = (params: any) => {
  currentPage.value = 1;
  searchParams.value = params;
  getList();
};

/**
 * 行操作处理
 * @param row 行数据
 * @param type 操作类型：'detail' | 'task'
 */

const action = (row: DepartmentUserItem, type: string) => {

  dialogTitle.value = type === "detail" ? "查看" : "创建采集任务";
  actionType.value = type;
  localStorage.setItem("collectorUserCode", row?.collectorUserCode || "");
  currentRow.value = {
    ...row,
    department: unref(treeEl)?.getCurrentNode() || {},
  };
  dialogVisible.value = true;
};

/**
 * 保存采集任务
 */
const saveTask = async () => {
  const task = unref(taskRef);
  if (!task) {
    ElMessage.error("无法获取选中的节点信息");
    return;
  }

  // 获取选中的节点和表单数据
  const checkedNodes = await task.getCheckedNodes();
  const formData = await task.submit();

  if (!formData) {
    ElMessage.warning("请正确填写表单");
    return;
  }

  if (!checkedNodes || checkedNodes.length === 0) {
    ElMessage.warning("请至少选择一个设备节点");
    return;
  }

  // 提取设备代码
  const deviceCodes = checkedNodes.map((node) => node.deviceCode);

  saveLoading.value = true;
  try {
    const res = await "/api/export/export".post(
      {
        deviceCatalogList: deviceCodes,
        ...formData,
      },
      {
        responseType: "blob", // 指定响应类型为blob用于文件下载
      }
    );
// console.log(res,123);

    // 处理文件下载
    await handleFileDownload(res);
    ElMessage.success("导出成功，文件已开始下载");
    dialogVisible.value = false;
    fetchDepartment(); // 刷新数据
  } catch (error) {
    // dialogVisible.value = false;


    // console.error("导出任务创建失败:", error);
    ElMessage.error("导出任务创建失败");
  } finally {
    saveLoading.value = false;
  }
};

/**
 * 处理文件下载
 * @param res 响应对象
 */
const handleFileDownload = async (res: any) => {
  const blob = new Blob([res.data], {
    type: res.headers["content-type"] || "application/octet-stream",
  });

  // 获取文件名
  const contentDisposition = res.headers["content-disposition"];
  let filename = "dataExport";
  if (contentDisposition) {
    const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
    if (filenameMatch && filenameMatch.length === 2) {
      filename = decodeURIComponent(filenameMatch[1]);
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();

  // 清理资源
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
};

/**
 * 处理文件导入
 * @param file 上传的文件对象
 */
const handleFileChange = async (file: UploadFile, type: string) => {
  if (!file.raw) {
    return;
  }

  selectedFile.value = file.raw;
  importLoading.value = true;

  try {
    const formData = new FormData();
    formData.append("file", file.raw);
    formData.append("deviceCode", currentNodeKey.value);
    let str =
      type === "packet" ? "/api/import/import" : "/excelImport/import";
    const res = await str.post(formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (res.code == 200) {
      ElMessage.success("导入成功");
      getList(); // 刷新表格
    } else if (res.code == 299) {
      // // 读取Excel文件
      //   const data = await readExcelFile(file.raw);
      console.log(res, "daoru");
      // 验证数据

      importResult.success = false;
      tabs.value = res.data;

      activeName.value = tabs.value[0].tab;
      // importResult.message = validationResult.message;
      // importResult.errors = validationResult.errors;
      resultDialogVisible.value = true;
      importLoading.value = false;
      return;
    }
  } catch (error: any) {
    console.error("导入错误:", error);

    ElMessage.warning(error.data?.msg || "导入失败");
  } finally {
    importLoading.value = false;
    // 清空文件选择
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
    selectedFile.value = null;
  }
};

/**
 * 读取Excel文件内容
 * @param file Excel文件
 * @returns 解析后的数据数组
 */


/**
 * 导出操作 - 打开创建采集任务对话框
 */
const exportAction = async () => {
  dialogTitle.value = "创建采集任务";
  dialogVisible.value = true;
  actionType.value = "task";
};

// ============ 生命周期 ============

/**
 * 组件挂载时初始化数据
 */
onMounted(() => {
  fetchDepartment();
});
</script>

<style scoped lang="less">
.el-card {
  // 卡片样式可以在这里定义
}

:deep(.el-divider--horizontal) {
  margin: 5px 0 15px 0;
}

.mb-10px {
  display: flex;
}

.opBtn-upload {
  display: inline-block;
  margin: 0 12px;
}

:deep(.el-tree-node__content) {
  height: 40px !important;
}

:deep(.is-current-node .el-tree-node .el-tree-node__content) {
  background-color: transparent !important;
  color: inherit !important;
  font-weight: normal;
}

:deep(.is-current-node > .el-tree-node__content) {
  background-color: var(--el-color-primary) !important;
  border-radius: 0 20px 20px 0;
  color: var(--el-tree-content-color) !important;
  font-weight: bold;
}

:deep(.el-tree) {
  background: transparent !important;
}
</style>
